package com.v1.video.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;

import com.iss.view.common.ToastAlone;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.BindInfo;
import com.v1.video.domain.Header;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.OptionInfo;
import com.v1.video.domain.PlayerInfo;
import com.v1.video.domain.ResultInfo;
import com.v1.video.domain.UploadInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.option.db.PersonalCenterUploadDB;
import com.v1.video.pay.MD5;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.view.Dialog3GUpload;
import com.v1.video.widgets.MyDialog;

/**
 * 传递参数 1.相关视频id（Constant.RELATED_VIDEO_ID）,不是添加视频时可以为空 2.原视频路径videoUri
 * 
 * @author 
 * 
 */
public class SaveShareActivity extends BaseActivity implements
		OnCheckedChangeListener {

	public final String TAG = "SaveShareActivity";

	private static final int REQUEST_CODE_VIDEO_COVER_EDIT = 101;
	private static final int REQUEST_CODE_ALBUM = 102;
	private static final int REQUEST_CODE_QUANZI = 103;
	private static final int REQUEST_CODE_FRIENDS = 104;
	private static final int REQUEST_CODE_CATALOG = 114;
	private static final int REQUEST_CODE_LOCATION = 115;
	private static final int REQUEST_CODE_LOGIN = 120;
	private static final int REQUEST_CODE_THEME = 121;//话题返回
	private static final long MAXMUN = 70; // 限制最多70个字
	private Dialog dialog;
	private TextView tv_location;
	private ImageView icon_location;

	/** 本地视频地址 */
	private Uri videoUri;
	private String relatedVideoId;

	private EditText et_title;
	private EditText et_content;
	private String first;
	private String second;
	private int ssotype;
	private ImageView tb_sina;
	private boolean isSina = false;
	private boolean isSinaBind = false;
	private ImageView tb_tenxun;
	private boolean isTenxun = false;
	private boolean isTenxunBind = false;
	private ImageView tb_qq;
	private boolean isQq = false;
	private boolean isQQBind = false;
	private ImageView tb_weixin;
	private boolean isweixin = false;
	private boolean isWeixinBind = false;
	private TextView contentNum;

//	private View mLoginLay;
	private View mLoginoutLay;
	
	private TextView mCatalogTxt;//分类
	
	//private View mAddTagLay;
	private TextView mTagTxt;
	
	//private View mAddQuanziLay;
//	private TextView mQuanziTxt;
	
	//private View mAddFriendsLay;
	private TextView mFriendTxt;

	private MediaPlayer mMediaPlayer;
	private long duration = -1;
	private String location = "";
	private String catalogName = "";//分类名称
	private String categoryId = "";//分类id
	private String albumName = "";//专辑名称
	private String groupId = "";//圈子id
	private String groupName = "";
	private String virtualAddress = "";//虚拟地理位置
	private ArrayList<PlayerInfo> listFriends = new ArrayList<PlayerInfo>();
	private String activityId = "";
	
	public static final int FROM_NOMAL = 0;//普通进入
	public static final int FROM_GROUP = 1;//从圈子进入
	public static final int FROM_ACTIVITY = 2;//从活动进入
	public static final int FROM_THEME = 3;//从话题进入
	public static String fromStr = "fromStr";
	public static String fromGroup = "fromGroup";
	public static String fromActivity = "fromActivity";
	public static String fromNormal = "fromNormal";
	public static String fromTheme = "fromTheme";
	private int from = 0;
	String scenario = "";
	
	private TextView txtTitle = null;
	private ImageView btnSaveShare = null;
	private LinearLayout layoutToLoginBack = null;//发布需登录
	
	private ImageView btnAddFriend = null;//@好友
	private TextView txtTheme = null;
	private String themeName = "";//话题名称
	private String themeId = "";//话题名称
	private String themes;
	private String version = "";
	private String packageName = "";
	
	private String videoWidth = "";
	private String videoHeight = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ShareSDK.initSDK(this);
		setContentView(R.layout.activity_save_share2);
	}

	@Override
	protected void initView() {
		tv_location = (TextView) findViewById(R.id.tv_location);
		icon_location = (ImageView) findViewById(R.id.imageView2);

		et_title = (EditText) findViewById(R.id.et_title);
		et_content = (EditText) findViewById(R.id.et_content);
		contentNum = (TextView) findViewById(R.id.tv_content_num);
		
//		mLoginLay=findViewById(R.id.loginLay);
		mLoginoutLay=findViewById(R.id.loginoutLay);
		
		mCatalogTxt = (TextView)findViewById(R.id.catalogTxt);
		
		//mAddTagLay = findViewById(R.id.addTagLay);
		mTagTxt = (TextView) findViewById(R.id.tagTxt);
		mFriendTxt = (TextView) findViewById(R.id.friendTxt);

		tb_sina = (ImageView) findViewById(R.id.tb_sina);
		tb_tenxun = (ImageView) findViewById(R.id.tb_tenxun);
		tb_qq = (ImageView) findViewById(R.id.tb_qq);
		tb_weixin = (ImageView) findViewById(R.id.tb_weixin);
		
		txtTitle = (TextView)findViewById(R.id.tv_title);
		btnSaveShare = (ImageView)findViewById(R.id.iv_right);
		
		layoutToLoginBack = (LinearLayout)findViewById(R.id.save_share_tologin_back);
		btnAddFriend = (ImageView)findViewById(R.id.imageView_add_friend);
		
		txtTheme = (TextView)findViewById(R.id.save_share_theme);
	}

	/* (non-Javadoc)
	 * @see com.iss.app.IssActivity#initData()
	 */
	@Override
	protected void initData() {
		if(LoginInfo.getInstance().isLogin()){
//			mLoginLay.setVisibility(View.VISIBLE);

			layoutToLoginBack.setVisibility(View.GONE);
			btnAddFriend.setVisibility(View.VISIBLE);
			mFriendTxt.setVisibility(View.VISIBLE);
			txtTheme.setVisibility(View.VISIBLE);
		}else{
//			mLoginLay.setVisibility(View.GONE);
			btnAddFriend.setVisibility(View.GONE);
			mFriendTxt.setVisibility(View.GONE);
			layoutToLoginBack.setVisibility(View.VISIBLE);
			txtTheme.setVisibility(View.GONE);
		}
		txtTitle.setText(R.string.share_title);
		btnSaveShare.setVisibility(View.VISIBLE);
		btnSaveShare.setImageResource(R.drawable.btn_share_save);
		// 获取参数信息
		Intent intent = getIntent();
		videoUri = intent.getParcelableExtra("videoUri");
		relatedVideoId = intent.getStringExtra(Constant.RELATED_VIDEO_ID);
		from = intent.getIntExtra(fromStr, FROM_NOMAL);
		//videoWidth = ""+XiaoyingUtils.getVideoWidth();
		//videoHeight = ""+XiaoyingUtils.getVideoHeight();
		videoWidth = ""+0;
		videoHeight = ""+0;
		Logger.i(TAG, "videoWidth=="+videoWidth);
		Logger.i(TAG, "videoHeight=="+videoHeight);
		Logger.i(TAG, "from=="+from);
		if(from == FROM_GROUP){
			groupName = intent.getStringExtra("groupName");
			groupId =  intent.getStringExtra("groupId");	
			relatedVideoId = fromGroup;
			scenario = groupId;
		}else if(from == FROM_ACTIVITY){
			groupName = intent.getStringExtra("groupName");
			groupId =  intent.getStringExtra("groupId");		
			activityId = intent.getStringExtra("activityId");
			relatedVideoId = fromActivity;
			scenario = activityId;
			Logger.i(TAG, "activityId="+activityId);
		}else if(from == FROM_THEME){
			themeName = intent.getStringExtra("themeName");
			themeId = intent.getStringExtra("themeId");
//			groupId =  intent.getStringExtra("groupId");		
//			activityId = intent.getStringExtra("activityId");
//			relatedVideoId = fromActivity;
			scenario = themeId;
			relatedVideoId = fromTheme;
			et_content.setText("#"+themeName+"#");
			Logger.i(TAG, "scenario="+scenario);
			Logger.i(TAG, "themeId="+themeId);
		}else{
			relatedVideoId = fromNormal;
			scenario = "";
		}
		Logger.i(TAG, "relatedVideoId="+relatedVideoId);
		Logger.i(TAG, "scenario="+scenario);
		et_title.setFilters(Utility.GetEmojiFilter());
		Utility.AddTextWatcher(et_title);
		et_content.setFilters(Utility.GetEmojiFilter());
		Utility.AddTextWatcher(et_content);
//		if (TextUtils.isEmpty(relatedVideoId)) {
//			relatedVideoId = "";
//		}
		
		// 获取视频长度信息
		getVideoDuration(videoUri);

		// 设置地址信息
//		SharedPreferences sp = getSharedPreferences(Constant.CURRENT_ADDRESS,
//				MODE_PRIVATE);
//
//		String province = sp.getString("province", "");
//		String city = sp.getString("city", "");
//		String district = sp.getString("district", "");
//
//		if (province.equals(city)) {
//			first = city;
//			second = district;
//		} else {
//			first = province;
//			second = city;
//		}
//		location = first + second;
		String firstAddr = "";//BaiduMapUtils.getLocationProp(this, "addrStr");
		if(!TextUtils.isEmpty(firstAddr)){
//			location=firstAddr;
			virtualAddress=firstAddr;
		}
//		tv_location.setText(location);
		tv_location.setText(virtualAddress);
		 PackageManager pm = getPackageManager();//context为当前Activity上下文 
	        PackageInfo pi;
	        try {
	            packageName = getPackageName();
	            pi = pm.getPackageInfo(packageName, 0);
	            version = pi.versionName;
	        } catch (NameNotFoundException e) {
	        }
	}

	@Override
	protected void setListener() {
		
		icon_location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		tv_location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				/*
				 * if (location.equals("")) { location = first + second;
				 * tv_location.setText(location); icon_location
				 * .setImageResource(R.drawable.location_label_light); } else {
				 * location = ""; tv_location.setText(location);
				 * icon_location.setImageResource(R.drawable.location_label); }
				 */
				
			}
		});
		et_content.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View arg0, int keyCode, KeyEvent arg2) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					hideSoftInput();
					return true;
				}
				return false;
			}
		});

		this.mTagTxt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				if(LoginInfo.getInstance().isLogin()){
					Intent intent = new Intent(SaveShareActivity.this,
							SelectAlbumActivity.class);
					SaveShareActivity.this.startActivityForResult(intent,
							REQUEST_CODE_ALBUM);
				}else{
					gotoLogin();
				}
			}
		});
		
		this.mCatalogTxt.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				clickStatistics(Constant.RELEASE_CLASSIFICATION_ID,"发布_选择分类");
				Intent intent = new Intent(SaveShareActivity.this,
						SelectCatalogActivity.class);
				intent.putExtra("data", catalogName);
				SaveShareActivity.this.startActivityForResult(intent,
						REQUEST_CODE_CATALOG);
			}});
		
		txtTheme.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				clickStatistics(Constant.RELEASE_TOPIC_ID,"发布_选择话题");
				Intent intent = new Intent(SaveShareActivity.this,
						SelectThemeActivity.class);
				SaveShareActivity.this.startActivityForResult(intent,
						REQUEST_CODE_THEME);
			}
		});
		
		this.mFriendTxt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(LoginInfo.getInstance().isLogin()){
					Intent intent2 = new Intent(SaveShareActivity.this,
							MyFriendsActivity.class);
					// intent2.putExtra("userId",
					// LoginInfo.getInstance().getUserID());32691
					intent2.putExtra("userId", LoginInfo.getInstance().getUserId());
					intent2.putExtra("isCanDouble", true);
					intent2.putExtra("flag", 1);
					SaveShareActivity.this.startActivityForResult(intent2,
							REQUEST_CODE_FRIENDS);
				}else{
					gotoLogin();
				}
			}
		});

		tb_sina.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {}
		});
		tb_tenxun.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {}
		});
		tb_qq.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {}
		});
		tb_weixin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {}
		});
		et_content.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				temp = s;
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String number = (MAXMUN - Utils.calculateLength(s)) + "个字";
				contentNum.setText(number);
				selectionStart = et_content.getSelectionStart();
				selectionEnd = et_content.getSelectionEnd();
				if (Utils.calculateLength(temp) > MAXMUN) {
					s.delete(
							(selectionStart - (int) (Utils.calculateLength(s) - MAXMUN)),
							selectionEnd);
					et_content.setText(s);
					et_content.setSelection(selectionStart);// 设置光标
				}
			}
		});
		
		layoutToLoginBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(LoginInfo.getInstance().isLogin()){
//					Intent intent_login = new Intent(SaveShareActivity2.this,
//							SettingLoginActivity.class);
//					intent_login.putExtra("loginFlag", 110);
//					startActivityForResult(intent_login, REQUEST_CODE_LOGIN);
//					Logger.i(TAG, "layoutToLoginBack准备去登录 了");
				}else{
					gotoLogin();
				}
				
			}
		});
		
		findViewById(R.id.loginoutLay).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//            	gotoLogin();
            	Intent i = new Intent(getApplicationContext(),
						SettingLoginActivity.class);
				i.putExtra("loginFlag", 110);
				startActivityForResult(i, REQUEST_CODE_LOGIN);
            }
        });
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            	finishActivity();
            }
        });
		btnSaveShare.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(LoginInfo.getInstance().isLogin()){
					submit(arg0);
				}else{
					gotoLogin();
				}
				
			}
		});

	}
	
	/**
	 * 是否放弃发布视频对话框
	 */
	private void finishActivity(){
		final MyDialog dg = Utility.createDialog(SaveShareActivity.this,
				R.style.dialog_custom);
		((TextView) dg.findViewById(R.id.tv_dialog_content))
				.setText("要放弃发布视频吗？");
		TextView cancel = (TextView) dg.findViewById(R.id.tv_dialog_cancel);
		TextView ok = (TextView) dg.findViewById(R.id.tv_dialog_ok);
		ok.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dg.dismiss();
				SaveShareActivity.this.finish();
			}
		});
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dg.dismiss();
			}
		});
		dg.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Logger.i(TAG, "返回到本页面了....222...");
		initUserInfo();
		MobclickAgent.onPageStart("发布");
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd("发布");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			btnSaveShare.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					finishActivity();
				}
			}, 300);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mMediaPlayer != null) {
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
		
	}

	/**
	 * 获取视频时长
	 * 
	 * @param outputUri
	 */
	private void getVideoDuration(Uri outputUri) {
		if (outputUri == null) {
			return;
		}
		try {
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					duration = mp.getDuration() / 1000;
					videoWidth = ""+mp.getVideoWidth();
					videoHeight = ""+mp.getVideoHeight();
					mp.getVideoHeight();
					if (mMediaPlayer != null) {
						mMediaPlayer.stop();
						mMediaPlayer.release();
						mMediaPlayer = null;
					}
				}
			});
			mMediaPlayer.setDataSource(SaveShareActivity.this, outputUri);
			mMediaPlayer.prepareAsync();
		} catch (Exception ex) {
			ex.printStackTrace();
			return;
		}

	}

	/**
	 * 分享视频
	 * 
	 * @param view
	 */
	public void submit(View view) {
		hideSoftInput();
		if (LoginInfo.getInstance().isLogin()) {

			// 发布视频
			publish();
		} else {// 提示用户登陆

			dialog = new Dialog(this, R.style.dialog_custom);
			dialog.setContentView(R.layout.dialog_promt_login);
			dialog.setCancelable(false);
			dialog.setCanceledOnTouchOutside(false);
			dialog.findViewById(R.id.close_account_cancel).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();

						}
					});
			dialog.findViewById(R.id.close_account_sure).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
							Intent i = new Intent(getApplicationContext(),
									SettingLoginActivity.class);
							i.putExtra("loginFlag", 110);
							startActivityForResult(i, REQUEST_CODE_LOGIN);

						}
					});
			dialog.show();
		}
	}

	private void publish() {

		// 场景， 北京市,海淀区 duration
		// UploadInfo.getInstance().clear();
		// UploadInfo.getInstance().setUserName(LoginInfo.getInstance().getUserName());
		// UploadInfo.getInstance().setDetail("detail111");//评论
		// UploadInfo.getInstance().setPlayNum("0");
		// UploadInfo.getInstance().setForward("0");
		// UploadInfo.getInstance().setComments("0");
		// UploadInfo.getInstance().setCreateTime("2014-5-9 18:00:00.0");
		// //当前时间注意格式
		// UploadInfo.getInstance().startUpload(this,
		// projectBean.Videos.get(0).File, "detail111", "12345", "title11",
		// "北京,海淀", Scenariolabelist[ScenariolabelistId]);
		if (UploadInfo.getInstance().isUploading()) {
			ToastAlone.showToast(SaveShareActivity.this, "您还有正在上传的视频，请稍后", 1);
			return;
		}
		final String videoTitle = et_title.getText().toString();
		final String videoCommit = et_content.getText().toString();

		if (TextUtils.isEmpty(videoTitle)) {
			Toast.makeText(this, "视频标题不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!Helper.checkConnection(SaveShareActivity.this)) {
			ToastAlone.showToast(SaveShareActivity.this, getResources()
					.getString(R.string.net_no), 1);
			return;
		}

		if (!Helper.isWifi(SaveShareActivity.this)) {
			// 判断设置的是否为所有网络上传，如果是toast提醒流量就可以，如果不是，则下面的提示框
			if (OptionInfo.getInstance(SaveShareActivity.this).isUploadAny()) {
				ToastAlone.showToast(SaveShareActivity.this, getResources()
						.getString(R.string.net_3g_upload), 1);
				// gotoPublish(videoTitle,videoCommit);
				publishOfJudge(videoTitle, videoCommit);
			} else {
				new Dialog3GUpload(SaveShareActivity.this)
						.show(new com.v1.video.view.Dialog3GUpload.OnConfirmAction() {

							@Override
							public void onConfirm() {
								// TODO Auto-generated method stub
								// gotoPublish(videoTitle,videoCommit);
								publishOfJudge(videoTitle, videoCommit);
							}
						});
			}
		} else {
			publishOfJudge(videoTitle, videoCommit);
			// gotoPublish(videoTitle,videoCommit);
		}
	}

	private void publishOfJudge(String title, String detail) {
//		String strJudge = "/^[\\u4e00-\\u9fa5\\w]+/";
		String strJudge = "^[\\u4e00-\\u9fa5\\w]+";
		Pattern pattern = Pattern.compile(strJudge);
		Matcher match = pattern.matcher(title);
		if(match.find()){
			new GetJudgeAsync(title, detail).execute();
//			ToastAlone.showToast(SaveShareActivity2.this, "可以上传了", 1);
		}else{
			ToastAlone.showToast(SaveShareActivity.this, "标题不能以符号开头！", 1);
		}		
	}

	private void gotoPublish(String videoTitle, String videoCommit) {
		String path = Utils.getRealFilePath(this, videoUri);
		if (TextUtils.isEmpty(path)) {
			return;
		}
		File file = new File(path);
		UploadInfo instance = UploadInfo.getInstance();
		
		StringBuffer friendsId = new StringBuffer();
		
		if(listFriends != null && listFriends.size() > 0){
			for(int i = 0 ; i< listFriends.size();i++){
				if(i == 0){
					friendsId.append(listFriends.get(i).getUserId());
				}else{
					friendsId.append(","+listFriends.get(i).getUserId());
				}
			}
		}
		String sourceId = UploadInfo.getUUID();
		
		themes = getThemes();
		if(from == FROM_THEME){
			if(themes.length() > 0 && !themes.contains("#") && themes.contains(themeName)){
			}else{
				relatedVideoId = fromNormal;
			}
		}
		String title = videoTitle;
	    String str[] = {"/","\"","[","]","%","&","_","(",")","<",">","{","}","@"};//,".",":",";"};
	    for(int i = 0; i < str.length;i++){
	    	if(title.contains(str[i])){
	    		Logger.i(TAG, "包含有"+str[i]+"了");
	    		title = title.replace(str[i], "");
	    	}
	    }
	    if(title.contains("'")){
	    	Logger.i(TAG, "包含有'了");
	    	title = title.replace("'", "");
	    }
	    
	    String detail = videoCommit;
	    for(int i = 0; i < str.length;i++){
	    	if(detail.contains(str[i])){
	    		Logger.i(TAG, "包含有"+str[i]+"了");
	    		detail = detail.replace(str[i], "");
	    	}
	    }
	    if(detail.contains("'")){
	    	Logger.i(TAG, "包含有'了");
	    	detail = detail.replace("'", "");
	    }
		Logger.i(TAG, "即将上传的话题为themes="+themes);
		String time = Utils.getSystemTime()+"";
		String uploadFileName = LoginInfo.getInstance().getUserId()+time;
		uploadFileName = MD5.getMessageDigest(uploadFileName);
		Logger.i(TAG, "uploadFileName="+uploadFileName);
		Header herder1 = new Header("headerMess", LoginInfo.getInstance()
				.getUserId(), uploadFileName, title, detail,
				// first + "," + second,
				location, scenario, duration + "", String.valueOf(file.length()),

				/* String.valueOf(file.getName()) */"mp4",
				sourceId, categoryId, "",
				albumName,groupId,friendsId.toString(),virtualAddress,activityId,
				themes,categoryId,"Android_"+version,videoWidth,videoHeight);
		herder1.filePath = file.getAbsolutePath();
		PersonalCenterUploadDB.getInstance(SaveShareActivity.this)
				.insertUploadInfo(herder1, SaveShareActivity.this);
		
		instance.startUpload(file.getAbsolutePath(), herder1,
				SaveShareActivity.this);
						
		int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
		getWindow().addFlags(flags);

		Intent center = new Intent(getApplicationContext(),
				UploadingVideoActivity.class);
		center.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		center.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		relatedVideoId = fromNormal;
		startActivity(center);
		finish();
	}
	
	private String getThemes(){
		String strDetail = et_content.getText().toString();
		char []arr = strDetail.toCharArray();
		int num = 0;
		for(int i = 0; i < arr.length;i++){
			if('#' == arr[i]){
				++num;
			}
		}
		if(num <= 1){
			return "";
		}else{
			int size = num / 2;
			String arrThemd[] = new String[size];
			int start = 0;
			int end = 0;
			for(int i = 0; i < size;i++){
				start = strDetail.indexOf("#", end==0?0:end+1);
				end = strDetail.indexOf("#", start+1);
				String s = strDetail.substring(start+1, end);
				arrThemd[i] = s;
			}
			ArrayList<String> listStr = new ArrayList<String>();
			for(int i = 0; i < arrThemd.length;i++){
				String temp = arrThemd[i];
				boolean isSame = false;
				for(int j = 0; j < listStr.size(); j++){
					String tempStr = listStr.get(j);
					if(temp.equals(tempStr)){
						isSame = true;
						break;
					}
				}
				if(!isSame){
					listStr.add(temp);
				}
			}
			StringBuilder themdInfo = new StringBuilder();
			for(int i = 0; i < listStr.size();i++){
				if (listStr.get(i).equals("")) {
					continue;
				}

				if (themdInfo.length() < 1) {
					themdInfo.append(listStr.get(i));
				} else {
					themdInfo.append("#").append(listStr.get(i));
				}
			}
			return themdInfo.toString();
		}
	}

	private void hideSoftInput() {
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(SaveShareActivity.this
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 保存到手机
	 * 
	 * @param view
	 */
	@Deprecated
	public void saveToSdcard(View view) {
		dialog = new Dialog(this, R.style.dialog_custom);
		dialog.setContentView(R.layout.dialog_save_video_to_sdcard);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.findViewById(R.id.close_account_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();

					}
				});
		dialog.show();
	}

/*	*//**
	 * 高级编辑
	 * 
	 * @param view
	 *//*
	public void seniorEdit(View view) {
		Intent intent = XiaoyingUtils.initAdvanceVideoEditIntent(
				SaveShareActivity2.this, videoUri);
		if (intent != null) {
			startActivityForResult(intent, Constant.REQUEST_CODE_VIDEO_ADV_EDIT);
		}

	}*/

	public void back(View view) {
		finish();
	}

	/**
	 * 设置封面
	 * 
	 * @param view
	 */
	public void setCover(View view) {
		// startActivityForResult(new Intent(getApplicationContext(),
		// FrontCoverActivity.class).putExtra("videoUri", videoUri),
		// REQUEST_CODE_VIDEO_COVER_EDIT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && data != null) {
			switch (requestCode) {
			case Constant.REQUEST_CODE_VIDEO_ADV_EDIT:
				Uri editVideoUri = data.getData();
				if (editVideoUri != null) {
					videoUri = editVideoUri;
					// XiaoyingUtils.insertRecord(SaveShareActivity2.this,
					// editVideoUri.toString());
				}
				break;
			case REQUEST_CODE_VIDEO_COVER_EDIT:
				Bitmap bitmap = data.getParcelableExtra("bitmap");
				// iv_cover.setImageBitmap(bitmap);
				break;
			case REQUEST_CODE_CATALOG:
				mCatalogTxt.setText(data.getExtras().getString("data").split("\\|")[0]);
				catalogName = data.getExtras().getString("data");
				categoryId = data.getExtras().getString("data").split("\\|")[1];
				Logger.i(TAG, "catalogName=="+catalogName+"_categoryId="+categoryId);
				break;
			case REQUEST_CODE_THEME://话题
				//添加话题
				String themeName = data.getExtras().getString("data");
				Logger.i(TAG, "返回的话题themdName="+themeName);
				if(themeName.length() > 0){
					String str = et_content.getText().toString();
					et_content.setText(str+"#"+themeName+"#");
//					if(themeOld.equals("")){
//						themeOld = themeName;
//						String str = et_content.getText().toString();
//						et_content.setText(str+"#"+themeOld+"#");
//					}else{
//						themeNew = themeName;
//						String str = et_content.getText().toString();
//						if(str.contains(themeOld)){
//							Logger.i(TAG, "str.contains(themeOld)");
//							str = str.replace("#"+themeOld+"#", "");
//							et_content.setText(str+"#"+themeNew+"#");
//							themeOld = themeNew;
//						}else{
//							et_content.setText(str+"#"+themeNew+"#");
//							themeOld = themeNew;
//						}
//					}
				}
				Logger.i(TAG, "获取话题的名称：themeName="+themeName);
				break;
			case REQUEST_CODE_ALBUM:
				mTagTxt.setText(data.getExtras().getString("data"));
				albumName = data.getExtras().getString("data");
				break;
			case REQUEST_CODE_QUANZI:
				groupId = data.getExtras().getString("groupId");
				break;
			case REQUEST_CODE_FRIENDS:
				if (data.getExtras().containsKey("listdata")) {
					Object obj = data.getExtras().getSerializable("listdata");
					if (obj != null) {
						ArrayList<PlayerInfo> listData = (ArrayList<PlayerInfo>) obj;
						listFriends.clear();
						listFriends.addAll(listData);
						mFriendTxt.setText(listData.size() + "位好友");
					}
				}
				break;
			case REQUEST_CODE_LOCATION:
				String str = data.getExtras().getString("data");
				tv_location.setText(str);
				
				if (str.equals("")) {
//					location = first + second;
					location = "";
					virtualAddress = "";
					tv_location.setText(location);
					icon_location
							.setImageResource(R.drawable.location_label);
				} else {
//					location = str;
					SharedPreferences sp = getSharedPreferences(Constant.CURRENT_ADDRESS,
							MODE_PRIVATE);

					String province = sp.getString("province", "");
					String city = sp.getString("city", "");
					String district = sp.getString("district", "");

					if (province.equals(city)) {
						first = city;
						second = district;
					} else {
						first = province;
						second = city;
					}
					location = first+second;
					virtualAddress = str;
					tv_location.setText(virtualAddress);
					icon_location.setImageResource(R.drawable.location_label_light);
				}
				
				break;
				
			case REQUEST_CODE_LOGIN:
				if(LoginInfo.getInstance().isLogin()){
//					mLoginLay.setVisibility(View.VISIBLE);
					layoutToLoginBack.setVisibility(View.GONE);
					mFriendTxt.setVisibility(View.VISIBLE);
					btnAddFriend.setVisibility(View.VISIBLE);
					txtTheme.setVisibility(View.VISIBLE);
				}else{
//					mLoginLay.setVisibility(View.GONE);
					layoutToLoginBack.setVisibility(View.VISIBLE);
					mFriendTxt.setVisibility(View.GONE);
					btnAddFriend.setVisibility(View.GONE);
					txtTheme.setVisibility(View.GONE);
				}
				break;
			}
		}
	}

	private void gotoLogin() {
		dialog = new Dialog(this, R.style.dialog_custom);
		dialog.setContentView(R.layout.dialog_promt_login);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.findViewById(R.id.close_account_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();

					}
				});
		dialog.findViewById(R.id.close_account_sure).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						Intent i = new Intent(getApplicationContext(),
								SettingLoginActivity.class);
						i.putExtra("loginFlag", 110);
						startActivityForResult(i, REQUEST_CODE_LOGIN);
					}
				});
		dialog.show();
	}

	private List<BindInfo> bangdinglist;

	private void initUserInfo() {
		if (LoginInfo.getInstance().isLogin()) {
			bangdinglist = LoginInfo.getInstance().getBangdinglist();
			if (bangdinglist != null && bangdinglist.size() > 0) {
				for (BindInfo bindinfo : bangdinglist) {
					if (bindinfo != null
							&& Constant.BINDING_TYPE_SINA.equals(bindinfo
									.getType())) {
						// 设置新浪打开
						isSinaBind = true;
						tb_sina.setImageResource(R.drawable.sina_ico);
						isSina = true;
						ssotype += 1;
					}
					if (bindinfo != null
							&& Constant.BINDING_TYPE_TENCENT.equals(bindinfo
									.getType())) {
						// 设置腾讯徽博打开
						isTenxunBind = true;
						tb_tenxun.setImageResource(R.drawable.tengxun_ico);
						isTenxun = true;
						ssotype += 2;
					}
					if (bindinfo != null
							&& Constant.BINDING_TYPE_QQ.equals(bindinfo
									.getType())) {
						// QQ空间
						isQQBind = true;
						tb_qq.setImageResource(R.drawable.icon_share_qq);
						isQq = true;
						ssotype += 2;
					}
					if (bindinfo != null
							&& Constant.BINDING_TYPE_WECHAT.equals(bindinfo
									.getType())) {
						// 微信
						isWeixinBind = true;
						tb_weixin.setImageResource(R.drawable.icon_share_weixin);
						isweixin = true;
						ssotype += 2;
					}
				}
			} else {
				bangdinglist = new ArrayList<BindInfo>();
				LoginInfo.getInstance().setBangdinglist(bangdinglist);
			}
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.tb_sina:
			if (isChecked) {
				ssotype += 1;
			} else {
				ssotype -= 1;
			}
			break;
		case R.id.tb_tenxun:
			if (isChecked) {
				ssotype += 2;
			} else {
				ssotype -= 2;
			}
			break;
		}
	}

	/**
	 * 检测版本
	 */
	private class GetJudgeAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";

		private ProgressDialog pd;
		ResultInfo resultInfo = null;
		String title = "";
		String detail = "";

		public GetJudgeAsync(String title, String detail) {
			this.title = title;
			this.detail = detail;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = Utils.getProgressDialog(SaveShareActivity.this,
					getResources().getString(R.string.get_data), this);
			pd.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				NetEngine engine = new NetEngine();
				resultInfo = engine.getUploadConJudge(title, detail);
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (pd != null && pd.isShowing()) {
				pd.cancel();
			}
			if (errorMsg.equals("")) {
				if (resultInfo != null) {
					if (resultInfo.getCode().equals("10")) {// code为11表示不含禁词
						ToastAlone.showToast(SaveShareActivity.this,
								resultInfo.getMessage(), 1);
					} else {
						gotoPublish(title, detail);
					}
				} else {
					ToastAlone
							.showToast(SaveShareActivity.this, getResources()
									.getString(R.string.exception_net), 1);
				}
			} else {
				ToastAlone.showToast(SaveShareActivity.this, errorMsg, 1);
			}
		}
	}
	
}
